<template>
  <div style="height: 100%;">
    <div v-loading="isLoading > 0" class="page-container">
      <page-tools>
        <template #search>
          <el-form
            ref="searchForm"
            size="mini"
            :inline="true"
            :model="searchForm"
            class="demo-form-inline"
          >
            <el-form-item label="商品类别id">
              <el-input v-model="searchForm.id" style="width: 100px;" />
            </el-form-item>
            <el-form-item label="商品类别名">
              <el-input v-model="searchForm.name" style="width: 100px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.prevent="onResetForm">清空</el-button>
              <el-button type="primary" @click.prevent="onSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </template>
        <template #right>
          <el-button type="primary" size="mini" @click="add">新增商品</el-button>
        </template>
      </page-tools>

      <el-card ref="appPageBody" class="app-page-body">
        <el-table height="100%" :data="goodsList" border size="mini">
          <el-table-column label="序号" type="index" :index="indexMethod" fixed="left" sortable />
          <el-table-column label="商品id" prop="id" />
          <el-table-column label="商品名称" prop="name" />
          <el-table-column label="商品描述" prop="goods_desc" width="80" />
          <el-table-column label="商品图片" width="100">
            <template #default="{ row }">
              <img :src="row.image" alt style="height: 60px;" />
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="price" />
          <el-table-column label="折后价" prop="discount_price" />
          <el-table-column label="特价" prop="special_price" />
          <el-table-column label="排名" prop="sort" />
          <el-table-column label="是否上线">
            <template #default="{ row }">
              <el-switch
                :value="row.status === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeStatus(row)"
              />
            </template>
          </el-table-column>
          <el-table-column class-name="handle-body" label="操作" width="180">
            <template #default="{ row }">
              <el-button type="primary" @click="edit(row)">编辑</el-button>
              <el-button type="danger" @click="del(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div class="pagination-body">
          <el-pagination
            :current-page="searchForm.page_num"
            :page-sizes="[10, 20, 30, 50, 100]"
            :page-size="searchForm.page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <add-edit ref="AddEditDialog" :cate-list="cateList" @refresh="getGoodsList" />
  </div>
</template>

<script>
import { getGoodsList, updateOneGoods, deleteOneGoods } from '@/api/goods'
import { getAllGoodsCategoryList } from '@/api/goods_category'
import AddEdit from './components/AddEdit'
import { toInt, initToPrice } from '@/utils/tools'

const searchForm = {
  id: undefined,
  name: undefined
}
// 处理数据类型（进来的时候处理一次，出去的时候处理一次，中间就不管了）
function handleSearchForm(obj) {
  obj.id = toInt(obj.id)
  obj.page_size = toInt(obj.page_size)
  obj.page_num = toInt(obj.page_num)
}
export default {
  name: 'GoodsList',
  components: {
    AddEdit
  },
  props: {},
  data() {
    return {
      isLoading: 0,
      searchForm: {},
      cateList: [],
      goodsList: [],
      total: 0
    }
  },
  computed: {},
  watch: {
    searchForm: {
      deep: true,
      handler(newVal) {
        this.changeQuery(newVal)
      }
    }
  },
  async created() {
    this.initSearchForm()
    this.getAllGoodsCategoryList()
    this.getGoodsList()
  },
  methods: {
    // search -------------------------------------------
    initSearchForm() {
      this.searchForm = Object.assign({}, searchForm, this.$route.query)

      // 进来的时候处理一次数据类型
      handleSearchForm(this.searchForm)
    },
    changeQuery(val) {
      // 获取当前的query参数
      const currentQuery = this.$route.query

      // 将新的筛选条件合并到query参数中
      const newQuery = Object.assign({}, currentQuery, val)

      // 使用Vue Router的replace方法更新URL
      this.$router.replace({ query: newQuery })
    },
    onResetForm() {
      this.searchForm = Object.assign({}, searchForm, {
        page_num: this.searchForm.page_num,
        page_size: this.searchForm.page_size
      })

      this.$refs.searchForm.resetFields()
      this.getGoodsList()
    },
    onSearch() {
      this.searchForm.page_num = 1

      this.getGoodsList()
    },
    // 获取各种数据 ------------------------------------
    async getAllGoodsCategoryList() {
      try {
        this.isLoading++
        this.cateList = await getAllGoodsCategoryList()
      } finally {
        this.isLoading--
      }
    },
    async getGoodsList() {
      try {
        this.isLoading++
        // 出去的时候处理一次数据类型
        handleSearchForm(this.searchForm)
        const res = await getGoodsList(this.searchForm)
        if (res.list.length === 0 && this.searchForm.page_num > 1) {
          this.searchForm.page_num--
          this.getGoodsList()
        } else {
          this.searchForm.page_num = res.page_num
          this.searchForm.page_size = res.page_size
          this.total = res.total
          // 处理数据
          res.list.forEach(item => {
            item.price = initToPrice(item.price)
            item.discount_price = initToPrice(item.discount_price)
            item.special_price = initToPrice(item.special_price)
            item.specs_list_json && (item.specs_list = JSON.parse(item.specs_list_json))
            item.compose_list_json && (item.compose_list = JSON.parse(item.compose_list_json))
          })
          this.goodsList = res.list
        }
      } finally {
        this.isLoading--
      }
    },
    // 渲染页面 --------------------------------------------
    indexMethod(index) {
      return index + 1 + (this.searchForm.page_num - 1) * this.searchForm.page_size
    },

    // 各种操作 --------------------------------------
    changeStatus(row) {
      this.$confirm('确定要进行次操作么？', '温馨提示').then(async() => {
        this.isLoading++
        await updateOneGoods({
          id: row.id,
          status: row.status === 1 ? -1 : 1
        })

        await this.getGoodsList()
        this.isLoading--
      })
    },
    edit(row) {
      this.$refs.AddEditDialog.open(row)
    },
    add() {
      this.$refs.AddEditDialog.open()
    },
    del(row) {
      this.$confirm('确定要进行次操作么？', '温馨提示').then(async() => {
        this.isLoading++
        await deleteOneGoods(row.id)
        await this.getGoodsList()
        this.isLoading--
      })
    },
    // 分页 -------------------------------------
    handleSizeChange(val) {
      this.searchForm.page_size = val
      this.getGoodsList()
    },
    handleCurrentChange(val) {
      this.searchForm.page_num = val
      this.getGoodsList()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
